<?php

define('PUN_ROOT', './');
require PUN_ROOT.'include/common.php';

if ($pun_user['g_read_board'] == '0')
	message($lang_common['No view']);

/*
 * runGallery() exits if G2 tells it to so (by isDone = true). It's important that you don't
 * output any html / anything before you call runGallery (which calls
 * GalleryEmbed::handleRequest), else, G2 won't work correctly.
 * Reason: G2 does a lot of redirects. E.g. when you login, it redirects to the next page, etc.
 * and redirects won't work if there was already some output before the redirect call.
 */
if ($pun_user['username'] == 'Guest')
{
	$data = runGallery('');
}
else
{
	$data = runGallery($pun_user['username']);
}

$page_title = pun_htmlspecialchars($data['title']);
define('PUN_EMBED_G2', 1);

require PUN_ROOT.'header.php';

echo $data['bodyHtml'];

require PUN_ROOT.'footer.php';


function runGallery($uid)
{
	global $pun_user;
	$data = array();

	// initiate G2 
	require(PUN_ROOT.'include/g2helper.php');
	$g2h = new g2helper();
	$ret = $g2h->init($uid, $pun_user['language']);
	if ($ret)
	{
		error('Unable to init gallery:'.$ret->getAsText());
	}

	// user interface: you could disable sidebar in G2 and get it as separate HTML to put it into a block
	// GalleryCapabilities::set('showSidebarBlocks', false);

	// handle the G2 request
	$g2moddata = GalleryEmbed::handleRequest();

	// show error message if isDone is not defined
	if (!isset($g2moddata['isDone']))
	{
		$data['bodyHtml'] = 'isDone is not defined, something very bad must have happened.';
		return $data;
	}
	// exit if it was an immediate view / request (G2 already outputted some data)
	if ($g2moddata['isDone'])
	{
		exit; 
	}

	// put the body html from G2 into the xaraya template 
	$data['bodyHtml'] = isset($g2moddata['bodyHtml']) ? $g2moddata['bodyHtml'] : '';

	// get the page title, javascript and css links from the <head> html from G2
	$title = ''; $javascript = array();	$css = array();

	if (isset($g2moddata['headHtml']))
	{
		list($data['title'], $css, $javascript) = GalleryEmbed::parseHead($g2moddata['headHtml']);
		$data['headHtml'] = $g2moddata['headHtml'];
	}


	/* Add G2 javascript  */
	$data['javascript'] = '';
	if (!empty($javascript))
	{
		foreach ($javascript as $script)
		{
			$data['javascript'] .= "\n".$script;
		}
	}

	/* Add G2 css  */
	$data['css'] = '';
	if (!empty($css))
	{
		foreach ($css as $style)
		{
			$data['css'] .= "\n".$style;
		}
	}

	// sidebar block
	if (isset($g2moddata['sidebarBlocksHtml']) && !empty($g2moddata['sidebarBlocksHtml']))
	{
		$data['sidebarHtml'] = $g2moddata['sidebarBlocksHtml'];
	}

	return $data;
} 

